<?php

namespace App\Services;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class BaoliaoQueryService
{
    protected $timeSharding;
    protected $popularitySharding;
    
    public function __construct(
        TimeBasedShardingService $timeSharding,
        PopularityBasedShardingService $popularitySharding
    ) {
        $this->timeSharding = $timeSharding;
        $this->popularitySharding = $popularitySharding;
    }
    
    /**
     * 安全的表查询方法
     */
    protected function safeTableQuery($table, $callback)
    {
        try {
            return DB::table($table)->tap($callback)->get();
        } catch (\Exception $e) {
            Log::warning("查询表 {$table} 失败: " . $e->getMessage());
            return collect([]);
        }
    }
    
    /**
     * 查询最新帖子
     */
    public function getLatestPosts($limit = 20, $page = 1)
    {
        $baseTable = 'baoliao_post';
        $tables = $this->timeSharding->getRecentTables($baseTable, 3); // 最近3个月的表
        
        // 如果没有时间分表，使用主表
        if (empty($tables)) {
            $tables = [$baseTable];
        }
        
        $results = [];
        $offset = ($page - 1) * $limit;
        
        // 按时间倒序从最近的表开始查询
        foreach ($tables as $table) {
            if (count($results) >= $limit) break;
            
            try {
                $query = DB::table($table)
                    ->orderBy('create_time', 'desc')
                    ->limit($limit - count($results));
                    
                if (!empty($results)) {
                    $lastResult = end($results);
                    $query->where('create_time', '<', $lastResult->create_time);
                }
                
                $tableResults = $query->get()->toArray();
                $results = array_merge($results, $tableResults);
            } catch (\Exception $e) {
                Log::warning("查询表 {$table} 失败: " . $e->getMessage());
                continue;
            }
        }
        
        return array_slice($results, 0, $limit);
    }
    
    /**
     * 查询最热帖子
     */
    public function getHottestPosts($limit = 20, $page = 1)
    {
        $baseTable = 'baoliao_post';
        $tables = $this->popularitySharding->getAllHotTables($baseTable);
        //dd($tables);
        //dd($baseTable);
        // 如果没有热度分表，使用主表
        if (empty($tables)) {
            $tables = [$baseTable];
        }
       // dd($tables);
        
        $results = [];
        $offset = ($page - 1) * $limit;
        
        // 从最热的表开始查询
        foreach ($tables as $table) {
            if (count($results) >= $limit) break;
            
            try {
                $query = DB::table($table)
                    ->orderByRaw('(like_count * 3 + comment_count * 2 + view_count) DESC')
                    ->limit($limit - count($results));
                    
                $tableResults = $query->get()->toArray();
                $results = array_merge($results, $tableResults);
            } catch (\Exception $e) {
                Log::warning("查询表 {$table} 失败: " . $e->getMessage());
                continue;
            }
        }
        
        // 对所有结果重新排序
        usort($results, function($a, $b) {
            $scoreA = ($a->like_count * 3) + ($a->comment_count * 2) + $a->view_count;
            $scoreB = ($b->like_count * 3) + ($b->comment_count * 2) + $b->view_count;
            return $scoreB - $scoreA;
        });
        
        return array_slice($results, $offset, $limit);
    }
    
    // 其他方法也需要类似的错误处理...
}
